package j20251112;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

// 实现 Callable 接口
class MyCallable implements Callable<String> {
    private final String name;

    public MyCallable(String name) {
        this.name = name;
    }

    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName() + " 开始执行任务: " + name);
        Thread.sleep(2000); // 模拟耗时操作
        System.out.println(Thread.currentThread().getName() + " 完成任务: " + name);
        return "任务 " + name + " 的执行结果";
    }
}

public class Demo5 {
    public static void main(String[] args) throws Exception {
        // 创建 Callable 实例
        Callable<String> callable = new MyCallable("测试任务");

        // 使用 FutureTask 包装 Callable
        FutureTask<String> futureTask = new FutureTask<>(callable);

        // 创建线程并启动
        Thread thread = new Thread(futureTask);
        thread.start();

        // 获取结果（会阻塞直到任务完成）
        String result = futureTask.get();
        System.out.println("任务结果: " + result);
    }
}
